const path = require('path');
const fs = require('fs');
const AudioProcessor = require('./processAudio');

// 检查文件夹是否已经处理过
function isFolderProcessed(htmlFilePath, overwrite = false) {
  try {
    // 生成输出文件路径
    const outputFilePath = htmlFilePath.replace('.htm', '_txt.html');
    
    // 如果允许覆盖，则认为未处理
    if (overwrite) {
      return false;
    }
    
    // 检查输出文件是否存在且包含转换后的语音内容标记
    if (fs.existsSync(outputFilePath)) {
      const outputContent = fs.readFileSync(outputFilePath, 'utf8');
      return outputContent.includes('[🎵语音内容]:');
    }
    
    // 如果输出文件不存在，检查原始文件是否已经处理过（向后兼容）
    if (!fs.existsSync(htmlFilePath)) return false;
    const htmlContent = fs.readFileSync(htmlFilePath, 'utf8');
    return htmlContent.includes('[语音内容]:') || htmlContent.includes('[🎵语音内容]:');
  } catch (error) {
    return false;
  }
}

// 批量处理多个文件夹的主函数（支持断点续传）
// folderName: 指定处理的特定文件夹名，不指定则处理所有
// overwrite: 是否覆盖已存在的转录文件
async function processBatchFolders(startFromIndex = 0, folderName = null, overwrite = false) {
  try {
    const dataDir = path.join(__dirname, 'data');
    
    // 如果指定了文件夹名，直接处理该文件夹
    if (folderName) {
      const specificFolderPath = path.join(dataDir, folderName);
      if (!fs.existsSync(specificFolderPath)) {
        throw new Error(`指定的文件夹不存在: ${folderName}`);
      }
      console.log(`处理指定文件夹: ${folderName}`);
      return await processSpecificFolder(specificFolderPath, folderName, overwrite);
    }
    
    // 获取data下的所有一级子文件夹
    const topLevelFolders = fs.readdirSync(dataDir, { withFileTypes: true })
      .filter(dirent => dirent.isDirectory())
      .map(dirent => dirent.name);
    
    console.log(`在data目录下找到 ${topLevelFolders.length} 个顶级文件夹: ${topLevelFolders.join(', ')}`);
    
    // 收集所有需要处理的子文件夹
    let allValidFolders = [];
    
    for (const topFolder of topLevelFolders) {
      const topFolderPath = path.join(dataDir, topFolder);
      console.log(`\n扫描顶级文件夹: ${topFolder}`);
      
      // 获取该顶级文件夹下的所有子文件夹
      const subFolders = fs.readdirSync(topFolderPath, { withFileTypes: true })
        .filter(dirent => dirent.isDirectory())
        .map(dirent => dirent.name);
      
      console.log(`  找到 ${subFolders.length} 个子文件夹`);
      
      // 检查哪些子文件夹包含必要的文件
      for (const subFolder of subFolders) {
        const subFolderPath = path.join(topFolderPath, subFolder);
        const htmlFilePath = path.join(subFolderPath, 'msg.htm');
        const voiceDir = path.join(subFolderPath, 'voice');
        
        if (fs.existsSync(htmlFilePath) && fs.existsSync(voiceDir)) {
          allValidFolders.push({
            name: `${topFolder}/${subFolder}`,
            folderPath: subFolderPath,
            htmlFilePath,
            voiceDir,
            topFolder,
            subFolder
          });
        }
      }
    }
    
    console.log(`\n找到 ${allValidFolders.length} 个有效文件夹（包含msg.htm和voice目录）`);
    
    const validFolders = allValidFolders;
    
    // 检查已处理的文件夹
    let processedCount = 0;
    let skippedFolders = [];
    
    for (let i = 0; i < validFolders.length; i++) {
      if (isFolderProcessed(validFolders[i].htmlFilePath, overwrite)) {
        processedCount++;
        if (i < startFromIndex) {
          skippedFolders.push(validFolders[i].name);
        }
      }
    }
    
    console.log(`📊 状态统计:`);
    console.log(`   已处理: ${processedCount} 个文件夹`);
    console.log(`   待处理: ${validFolders.length - processedCount} 个文件夹`);
    
    if (startFromIndex > 0) {
      console.log(`🚀 断点续传: 从第 ${startFromIndex + 1} 个文件夹开始处理`);
      if (skippedFolders.length > 0) {
        console.log(`⏭️  跳过已处理的文件夹: ${skippedFolders.length} 个`);
      }
    }
    
    // 显示即将处理的文件夹
    const foldersToProcess = validFolders.slice(startFromIndex);
    console.log(`\n📋 将要处理的文件夹 (从第${startFromIndex + 1}个开始):`);
    foldersToProcess.slice(0, 5).forEach((folder, index) => {
      const globalIndex = startFromIndex + index + 1;
      const status = isFolderProcessed(folder.htmlFilePath, overwrite) ? '✅已处理' : '⏳待处理';
      console.log(`${globalIndex}. ${folder.name} ${status}`);
    });
    
    if (foldersToProcess.length > 5) {
      console.log(`   ... 还有 ${foldersToProcess.length - 5} 个文件夹`);
    }
    
    // 处理文件夹
    let successCount = 0;
    let errorCount = 0;
    let actuallyProcessed = 0;
    
    for (let i = startFromIndex; i < validFolders.length; i++) {
      const folder = validFolders[i];
      const currentIndex = i + 1;
      
      console.log(`\n[${currentIndex}/${validFolders.length}] 检查文件夹: ${folder.name}`);
      
      // 检查是否已经处理过
      if (isFolderProcessed(folder.htmlFilePath, overwrite)) {
        console.log(`⏭️  跳过已处理的文件夹: ${folder.name}`);
        successCount++;
        continue;
      }
      
      console.log(`🔄 开始处理: ${folder.name}`);
      
      try {
        // 创建音频处理器实例，传递覆盖参数
        const processor = new AudioProcessor(folder.htmlFilePath, folder.voiceDir, overwrite);
        
        // 开始处理
        await processor.process();
        successCount++;
        actuallyProcessed++;
        
        console.log(`✅ 处理完成: ${folder.name} (实际处理第${actuallyProcessed}个)`);
        
        // 保存进度
        const progressInfo = {
          timestamp: new Date().toISOString(),
          lastProcessedIndex: i,
          totalFolders: validFolders.length,
          successCount: successCount,
          actuallyProcessed: actuallyProcessed
        };
        
        fs.writeFileSync('progress.json', JSON.stringify(progressInfo, null, 2));
        
        // 添加延迟以避免过度频繁的API调用，并进行内存清理
        if (i < validFolders.length - 1) {
          console.log('等待2秒后处理下一个文件夹...');
          
          // 定期执行垃圾回收（每5个文件夹）
          if (actuallyProcessed % 5 === 0) {
            console.log('🧹 执行内存清理...');
            if (global.gc) {
              global.gc();
            }
            
            // 检查内存使用情况
            const memUsage = process.memoryUsage();
            const memUsedMB = Math.round(memUsage.heapUsed / 1024 / 1024);
            console.log(`📊 当前内存使用: ${memUsedMB}MB`);
            
            // 如果内存使用超过阈值，增加延迟
            if (memUsedMB > 800) {
              console.log('⚠️  内存使用较高，延长等待时间到10秒');
              await new Promise(resolve => setTimeout(resolve, 10000));
            } else {
              await new Promise(resolve => setTimeout(resolve, 2000));
            }
          } else {
            await new Promise(resolve => setTimeout(resolve, 2000));
          }
        }
        
      } catch (error) {
        console.error(`❌ 处理失败: ${folder.name}`, error.message);
        errorCount++;
      }
    }
    
    console.log(`\n🎉 批量处理完成！`);
    console.log(`📊 最终统计:`);
    console.log(`   📁 文件夹总数: ${validFolders.length}`);
    console.log(`   ✅ 成功处理: ${successCount}`);
    console.log(`   ❌ 处理失败: ${errorCount}`);
    console.log(`   🔄 本次实际处理: ${actuallyProcessed}`);
    console.log(`   📈 成功率: ${(successCount/validFolders.length*100).toFixed(1)}%`);
    
  } catch (error) {
    console.error('批量处理程序执行失败:', error);
    process.exit(1);
  }
}

// 处理指定文件夹的函数
async function processSpecificFolder(folderPath, folderName, overwrite = false) {
  try {
    console.log(`开始处理指定文件夹: ${folderName}`);
    
    // 检查是否是顶级文件夹（需要遍历其子文件夹）
    const htmlFilePath = path.join(folderPath, 'msg.htm');
    const voiceDir = path.join(folderPath, 'voice');
    
    if (fs.existsSync(htmlFilePath) && fs.existsSync(voiceDir)) {
      // 这是一个包含msg.htm和voice的文件夹，直接处理
      console.log(`处理文件夹: ${folderName}`);
      
      if (isFolderProcessed(htmlFilePath, overwrite)) {
        console.log(`⏭️  文件夹已处理过: ${folderName}`);
        return { success: 1, skipped: 1, processed: 0 };
      }
      
      const processor = new AudioProcessor(htmlFilePath, voiceDir, overwrite);
      await processor.process();
      console.log(`✅ 处理完成: ${folderName}`);
      return { success: 1, skipped: 0, processed: 1 };
      
    } else {
      // 这是一个顶级文件夹，需要处理其子文件夹
      const subFolders = fs.readdirSync(folderPath, { withFileTypes: true })
        .filter(dirent => dirent.isDirectory())
        .map(dirent => dirent.name);
      
      console.log(`文件夹 ${folderName} 包含 ${subFolders.length} 个子文件夹`);
      
      let totalSuccess = 0;
      let totalSkipped = 0;
      let totalProcessed = 0;
      
      for (const subFolder of subFolders) {
        const subFolderPath = path.join(folderPath, subFolder);
        const subHtmlFilePath = path.join(subFolderPath, 'msg.htm');
        const subVoiceDir = path.join(subFolderPath, 'voice');
        
        if (fs.existsSync(subHtmlFilePath) && fs.existsSync(subVoiceDir)) {
          console.log(`处理子文件夹: ${folderName}/${subFolder}`);
          
          if (isFolderProcessed(subHtmlFilePath, overwrite)) {
            console.log(`⏭️  子文件夹已处理过: ${subFolder}`);
            totalSkipped++;
            continue;
          }
          
          try {
            const processor = new AudioProcessor(subHtmlFilePath, subVoiceDir, overwrite);
            await processor.process();
            console.log(`✅ 子文件夹处理完成: ${subFolder}`);
            totalSuccess++;
            totalProcessed++;
            
            // 添加延迟和内存管理
            if (subFolder !== subFolders[subFolders.length - 1]) {
              console.log('等待2秒后处理下一个文件夹...');
              
              // 定期内存清理
              if (totalProcessed % 3 === 0) {
                if (global.gc) {
                  global.gc();
                  console.log('🧹 执行内存清理');
                }
                
                const memUsage = process.memoryUsage();
                const memUsedMB = Math.round(memUsage.heapUsed / 1024 / 1024);
                console.log(`📊 内存使用: ${memUsedMB}MB`);
                
                if (memUsedMB > 600) {
                  console.log('⚠️  延长等待时间');
                  await new Promise(resolve => setTimeout(resolve, 5000));
                } else {
                  await new Promise(resolve => setTimeout(resolve, 2000));
                }
              } else {
                await new Promise(resolve => setTimeout(resolve, 2000));
              }
            }
          } catch (error) {
            console.error(`❌ 子文件夹处理失败: ${subFolder}`, error.message);
          }
        }
      }
      
      console.log(`\n📊 ${folderName} 处理统计:`);
      console.log(`   ✅ 成功处理: ${totalSuccess}`);
      console.log(`   ⏭️  已跳过: ${totalSkipped}`);
      console.log(`   🔄 本次实际处理: ${totalProcessed}`);
      
      return { success: totalSuccess + totalSkipped, skipped: totalSkipped, processed: totalProcessed };
    }
  } catch (error) {
    console.error(`处理文件夹失败: ${folderName}`, error);
    throw error;
  }
}

// 原始的单个文件夹处理函数（保留用于测试）
async function processSingleFolder() {
  try {
    // 配置文件路径
    const htmlFilePath = path.join(__dirname, 'data', '？ 终究？？是戏？(7881302389007185)', 'msg.html');
    const voiceDir = path.join(__dirname, 'data', '？ 终究？？是戏？(7881302389007185)', 'voice');
    
    console.log('HTML文件路径:', htmlFilePath);
    console.log('语音文件目录:', voiceDir);
    
    // 创建音频处理器实例
    const processor = new AudioProcessor(htmlFilePath, voiceDir);
    
    // 开始处理
    await processor.process();
    
  } catch (error) {
    console.error('程序执行失败:', error);
    process.exit(1);
  }
}

// 主函数 - 默认使用批量处理
async function main() {
  const args = process.argv.slice(2);
  
  // 检查是否启用覆盖模式
  const overwrite = args.includes('--overwrite') || args.includes('--force');
  if (overwrite) {
    console.log('🔄 覆盖模式已启用，将重新生成所有转录文件');
  }
  
  // 检查是否指定了特定文件夹
  const folderIndex = args.findIndex(arg => arg === '--folder');
  if (folderIndex !== -1 && args[folderIndex + 1]) {
    const folderName = args[folderIndex + 1];
    console.log(`处理指定文件夹模式: ${folderName}`);
    await processBatchFolders(0, folderName, overwrite);
    return;
  }
  
  if (args.includes('--single')) {
    console.log('使用单个文件夹处理模式');
    await processSingleFolder();
  } else if (args.includes('--continue')) {
    // 断点续传模式
    let startIndex = 45; // 默认从第46个开始（索引从0开始）
    
    // 检查是否指定了起始位置
    const continueIndex = args.findIndex(arg => arg === '--continue');
    if (continueIndex !== -1 && args[continueIndex + 1]) {
      const specifiedIndex = parseInt(args[continueIndex + 1]) - 1; // 转换为0基索引
      if (!isNaN(specifiedIndex) && specifiedIndex >= 0) {
        startIndex = specifiedIndex;
      }
    }
    
    // 尝试从进度文件中读取上次的位置
    try {
      if (fs.existsSync('progress.json')) {
        const progress = JSON.parse(fs.readFileSync('progress.json', 'utf8'));
        console.log(`📄 发现进度文件:`);
        console.log(`   上次处理时间: ${progress.timestamp}`);
        console.log(`   上次处理到: 第${progress.lastProcessedIndex + 1}个文件夹`);
        console.log(`   已成功处理: ${progress.successCount}个`);
        console.log(`   实际处理: ${progress.actuallyProcessed}个`);
        
        startIndex = progress.lastProcessedIndex + 1;
      }
    } catch (error) {
      console.log('无法读取进度文件，使用指定的起始位置');
    }
    
    console.log(`🚀 断点续传模式: 从第 ${startIndex + 1} 个文件夹开始处理`);
    await processBatchFolders(startIndex, null, overwrite);
  } else {
    console.log('使用批量文件夹处理模式（处理data下所有文件夹）');
    await processBatchFolders(0, null, overwrite);
  }
}

// 如果直接运行此文件，则执行main函数
if (require.main === module) {
  main();
}

module.exports = { main };